//
//  YGKPathTrackController.m
//  PathTrack
//
//  Created by YGK on 16/7/5.
//  Copyright © 2016年 YGK. All rights reserved.
//

#import "YGKPathTrackController.h"

@interface YGKPathTrackController ()<CLLocationManagerDelegate,NSFetchedResultsControllerDelegate>
{
    NSString *token_str;
}
@property (weak, nonatomic) IBOutlet UILabel *currentLocationLabel;
@property (weak, nonatomic) IBOutlet UILabel *enterStationLabel;
@property (weak, nonatomic) IBOutlet UILabel *passPointLabel;
@property (weak, nonatomic) IBOutlet UILabel *exitStationLabel;
@property (weak, nonatomic) IBOutlet UIButton *reservationButton;
- (IBAction)reservationAction:(id)sender;
@property (weak, nonatomic) IBOutlet UISwitch *isEnteredStationSwitch;
- (IBAction)isEnterdSationAction:(id)sender;
@property (weak, nonatomic) IBOutlet UISwitch *isLeftSationSwitch;
- (IBAction)leftStationAction:(id)sender;
- (IBAction)statusResetAction:(id)sender;

@property (nonatomic) NSFetchedResultsController *fetchedResultsController;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UILabel *drivingState;

@property (nonatomic,strong) CLLocationManager *locationManager;

@property (nonatomic,strong) NSMutableArray *stationPointsArray;
@property (nonatomic,strong) NSMutableArray *flagPointsArray;

@property (nonatomic,copy) NSString *currentPointName;
@property (nonatomic,copy) NSString *lastPointName;
@property (nonatomic,assign) int checkTimes;
@property (nonatomic,assign) BOOL uploaded;
@property (nonatomic,strong) NSMutableArray *checkedPointsArrary;

@end

@implementation YGKPathTrackController

-(CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
//        _locationManager.allowsBackgroundLocationUpdates = YES;
        [_locationManager requestAlwaysAuthorization];
    }
    return _locationManager;
}
- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController) return _fetchedResultsController;
    
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"TargetPoint"];
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"flag_id" ascending:YES];
    fetchRequest.sortDescriptors = @[sort];
    
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[HMDataManager sharedManager].managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    
    _fetchedResultsController.delegate = self;
    
    return _fetchedResultsController;
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {

}
-(void) getStationAndFlagPoints {
    self.fetchedResultsController.fetchRequest.predicate = nil;
    [self.fetchedResultsController performFetch:NULL];
    self.stationPointsArray = [NSMutableArray arrayWithCapacity:10];
    self.flagPointsArray = [NSMutableArray arrayWithCapacity:10];
    for (TargetPoint *point in self.fetchedResultsController.fetchedObjects) {
        if ([point.type  isEqual: @1]) {
            [self.stationPointsArray addObject:point];
        }else{
            if ([point.type  isEqual: @2]) {
                [self.flagPointsArray addObject:point];
            }
        }
    }
}
//获取token
-(void)login
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"mobile"] = @"13671743863";
    dic[@"password"] = @"1231";
    dic[@"plat_form"] = @"3";
    dic[@"app_version"] = @"1.0";
    dic[@"device_token"] = @"1233";
    NSString *para_str = [NSString dictionaryToJson:dic];
    
    NSMutableDictionary *parametrs = [[NSMutableDictionary alloc] init];
    parametrs[@"sign"] = para_str;
    
    NSString *loginUrl = [NSString stringWithFormat:@"http://120.76.154.75/app/api/member/login"];
    NSLog(@"\n登录请求参数:%@",parametrs);
    
    [[YGKNetworking sharedYGKNetworking] POST:loginUrl parameters:parametrs success:^(id  _Nonnull responseObject) {
        NSDictionary *post_dic = [NSDictionary dictionaryWithDictionary:responseObject];
        NSLog(@"\n\nPOST_SUCCESS≈≈≈≈≈≈≈≈≈≈%@",post_dic);
        int result = [post_dic[@"code"] intValue];
        if (result == 0) {
            [MBProgressHUD showSuccess:@"登录成功" toView:self.view];
            [self.loginButton setTitle:@"已登录" forState:UIControlStateNormal];
        }else{
            [MBProgressHUD showError:@"登录失败" toView:self.view];
        }
        NSDictionary *data_dic = post_dic[@"data"];
        NSString *token_string = data_dic[@"token"];
        NSLog(@"获得token:%@",token_string);
        token_str = token_string;
        
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"\n\nPOST_FAILURE_____________%@",error);
        [MBProgressHUD showError:@"请求失败" toView:self.view];

    }];
}

//预约
-(void)appointRequest
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"token"] = token_str;
    dic[@"car_id"] = @"353";
    NSString *para_str = [NSString dictionaryToJson:dic];
    
    NSMutableDictionary *parametrs = [[NSMutableDictionary alloc] init];
    parametrs[@"sign"] = para_str;
    
    NSString *appointUrl = [NSString stringWithFormat:@"http://120.76.154.75/app/api/car/reserve"];
    NSLog(@"\n预约请求参数:%@",parametrs);
    
    [[YGKNetworking sharedYGKNetworking] POST:appointUrl parameters:parametrs success:^(id  _Nonnull responseObject) {
        NSDictionary *post_dic = [NSDictionary dictionaryWithDictionary:responseObject];
        NSLog(@"\n\nPOST_SUCCESS预约≈≈≈≈≈≈≈≈≈%@",post_dic);
        int result = [post_dic[@"code"] intValue];
        if (result == 0) {
            [MBProgressHUD showSuccess:@"预约成功" toView:self.view];
        }else{
            [MBProgressHUD showError:@"预约失败" toView:self.view];
        }
        
//        [self uploadIdentificationPointRequest:@[@"2",@"3"]];
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"\n\nPOST_FAILURE_____________%@",error);
        [MBProgressHUD showError:@"请求失败" toView:self.view];
    }];
}
//上传标识点
-(void)uploadIdentificationPointRequest:(NSArray *)array
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"token"] = token_str;
    //数组转为字符串
    dic[@"point_id"] = [array componentsJoinedByString:@","];
    NSString *para_str = [NSString dictionaryToJson:dic];
    
    NSMutableDictionary *parametrs = [[NSMutableDictionary alloc] init];
    parametrs[@"sign"] = para_str;
    
    NSString *path_pointUrl = [NSString stringWithFormat:@"http://120.76.154.75/app/api/car/pointReport"];
    NSLog(@"\n上传请求参数:%@",parametrs);

    [[YGKNetworking sharedYGKNetworking] POST:path_pointUrl parameters:parametrs success:^(id  _Nonnull responseObject) {
        NSDictionary *post_dic = [NSDictionary dictionaryWithDictionary:responseObject];
        NSLog(@"\n\nPOST_SUCCESS上传≈≈≈≈≈≈≈≈≈%@",post_dic);
        NSString *status_str = [NSString stringWithFormat:@"%@",post_dic[@"data"][@"status"]];
        int result = [post_dic[@"code"] intValue];
        if (result == 0) {
            [MBProgressHUD showSuccess:@"上传标识点成功" toView:self.view];
            self.drivingState.text = status_str;      //行驶状态
        }else{
            [MBProgressHUD showError:@"上传标识点失败" toView:self.view];
        }
        NSLog(@"____%@",status_str);
        
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"\n\nPOST_FAILURE_____________%@",error);
        [MBProgressHUD showError:@"请求失败" toView:self.view];

    }];
    
    /**
     把所有的标志点存到一个本地文件中
     *
     */
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDateFormatter *detail_formatter = [[NSDateFormatter alloc] init];
    [detail_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *fileName = [NSString stringWithFormat:@"%@.txt",[formatter stringFromDate:[NSDate date]]];   //文件名
    NSString *recordTime = [detail_formatter stringFromDate:[NSDate date]];               //该条请求的时间
    NSString *fileNamePath = [DEF_DocumentsDir stringByAppendingPathComponent:fileName];  //文件路径
    NSString *flag_string = [array componentsJoinedByString:@","];                        //站点
    NSString *content = [NSString stringWithFormat:@"%@经过的标识点:%@",recordTime,flag_string];      //要存储到文件中的信息
    NSError*error =nil;
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL file_exit = [fileManager fileExistsAtPath:fileNamePath];
    if (file_exit) {      //文件存在
        NSMutableString *sandBox_string = [NSMutableString stringWithContentsOfFile:fileNamePath encoding:NSUTF8StringEncoding error:&error];
        [sandBox_string appendFormat:@"\n%@",content];
        [sandBox_string writeToFile:fileNamePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    }else{                //文件不存在
        [content writeToFile:fileNamePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    }
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
     [self getStationAndFlagPoints];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.isEnteredStationSwitch setOn:NO];
    self.isEnteredStationSwitch.enabled = NO;
    [self.isLeftSationSwitch setOn:NO];
    self.isLeftSationSwitch.enabled = NO;
    self.checkTimes = 0;
    self.uploaded = NO;
//    for (TargetPoint *point in self.stationPointsArray) {
//        MYLog(@"flag_id: %@ ,%@,%@,%@",point.flag_id,point.y_code,point.x_code,point.type);
//    }for (TargetPoint *point in self.flagPointsArray) {
//        MYLog(@"flag_id: %@ ,%@,%@,%@",point.flag_id,point.y_code,point.x_code,point.type);
//    }
    
}
- (IBAction)login:(id)sender {
    [self login];        //登录获取token

}


- (IBAction)reservationAction:(id)sender {
    self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
//    self.locationManager.distanceFilter = 100;
    self.locationManager.pausesLocationUpdatesAutomatically = NO;
    [self.locationManager startUpdatingLocation];
    self.reservationButton.enabled = NO;
    [self.reservationButton setTitle:@"已预约" forState:UIControlStateDisabled];
    
    
    [self appointRequest];         //预约
    
}
- (IBAction)isEnterdSationAction:(id)sender {
    self.isEnteredStationSwitch.enabled = NO;
}
- (IBAction)leftStationAction:(id)sender {
    self.isLeftSationSwitch.enabled = NO;
    [self.locationManager stopUpdatingLocation];
    self.exitStationLabel.text = @"出站点信息由服务器提供";
    self.currentLocationLabel.text = @"出站后手机停止定位";
}

- (IBAction)statusResetAction:(id)sender {
    [self.locationManager stopUpdatingLocation];
    self.currentLocationLabel.text = nil;
    self.enterStationLabel.text = nil;
    self.passPointLabel.text = @""; // 此处不为nil是因为后面要调用添加字符串方法
    self.exitStationLabel.text = nil;
    self.isEnteredStationSwitch.on = NO;
    self.isEnteredStationSwitch.enabled = NO;
    [self.isLeftSationSwitch setOn:NO];
    self.isLeftSationSwitch.enabled = NO;
    self.checkTimes = 0;
    self.uploaded = NO;
    self.currentPointName = nil;
    self.lastPointName = nil;
    self.reservationButton.enabled = YES;
    [self.reservationButton setTitle:@"一键预约" forState:UIControlStateNormal];
    
}

#pragma mark CLLocationManagerDelegate 方法

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *currentLocation = locations.firstObject;
    NSMutableArray *allPoints = self.stationPointsArray.mutableCopy;
    [allPoints addObjectsFromArray:self.flagPointsArray];
    double minDistance = 88888888;
    NSString *minPointName;
    for (TargetPoint *point in allPoints) {
        CLLocation *targertLocation = [[CLLocation alloc]initWithLatitude:point.y_code.floatValue longitude:point.x_code.floatValue];
        double distance = [targertLocation distanceFromLocation:currentLocation];
        if (distance < minDistance) {
            minDistance = distance;
            minPointName = point.flag_id;
        }
    }
    
    self.currentLocationLabel.text = [NSString stringWithFormat:@"纬度:%.6f 经度:%.6f    与最近点“%@”距离%.0f米",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude,minPointName,minDistance];
    if (self.isEnteredStationSwitch.on == YES) {
        self.isLeftSationSwitch.enabled = YES;
    }
    if (self.isEnteredStationSwitch.on == NO) {
        for (TargetPoint *point in self.stationPointsArray) {
            CLLocation *targetLocation = [[CLLocation alloc]initWithLatitude:point.y_code.floatValue longitude:point.x_code.floatValue];
            double distance = [targetLocation distanceFromLocation:currentLocation];
            if (distance <= 300 ) {
                self.isEnteredStationSwitch.enabled = YES;
                self.enterStationLabel.text = point.flag_id;
            }
        }
    }else {
        if (self.isEnteredStationSwitch.on == YES ) {
            for (TargetPoint *point in self.flagPointsArray) {
                CLLocation *targetLocation = [[CLLocation alloc]initWithLatitude:point.y_code.floatValue longitude:point.x_code.floatValue];
                double distance = [targetLocation distanceFromLocation:currentLocation];
                if (distance <= 300 ) {
                    self.currentPointName = point.flag_id;
                    if (self.currentPointName == self.lastPointName) {
                        self.checkTimes ++;
                        if (self.checkTimes >= 3 && self.uploaded == NO) {
                            //上传检测到的标识点
                            self.uploaded = YES;
                            self.passPointLabel.text = [self.passPointLabel.text stringByAppendingString:[NSString stringWithFormat:@"%@-%d次,",self.currentPointName,self.checkTimes]];
                            
                            //上传标识点
                            NSArray *arr = [NSArray arrayWithObject:self.currentPointName];
                            [self uploadIdentificationPointRequest:arr];
                        }
                    } else {
                        if (self.lastPointName != nil) {
                            // 构造记录模型，保存经过每一标识点的检测次数
                             YGKCheckModel *checkModel = [[YGKCheckModel alloc]init];
                            checkModel.name = self.lastPointName;
                            checkModel.checkTimes = self.checkTimes;
                            [self.checkedPointsArrary addObject:checkModel];
                            
                        }
                        self.checkTimes = 1;
                       
                        self.uploaded = NO;
                        self.lastPointName = self.currentPointName;
                    }
//                    self.passPointLabel.text = [self.passPointLabel.text stringByAppendingString:[NSString stringWithFormat:@" %@",point.flag_id]];
                }
            }

        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
//#pragma mark - Table view data source
//
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
//    return 0;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
//    return 0;
//}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/




@end
